package netty.demo3.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Demo3Client {
    public static void main(String[] args) throws InterruptedException {
        connect("zhangsan");
        connect("lisi");
        connect("wangwu");
    }

    public static void connect(String message) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        Channel channel = bootstrap.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        System.out.println("init.........");
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                }).connect("127.0.0.1", 8080)
                .sync().channel();

        channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(message.getBytes()));

        Thread.sleep(2000);

        channel.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(message.getBytes()));
    }
}
